# coding=utf-8

'''
Created on Feb 15, 2011

@author: alexey@kinobaza.tv
'''
import hashlib
import base64
import string
import time

import json
import httplib

import oauth2 as oauth 

import urlparse
import urllib

AUTH_URL = "http://api.kinobaza.local/auth"

API_DOMAIN = "http://api.kinobaza.local"
API_HOST = "api.kinobaza.local"
    
class ApiClient(object):
    def __init__(self, consumer_key, consumer_secret ):
        self.oauth_consumer = oauth.Consumer(consumer_key, consumer_secret)
        
    def getRequestToken(self):
        client = oauth.Client(self.oauth_consumer)
        resp, content = client.request(AUTH_URL + '/request-token', "GET")
        
        if resp['status'] != '200':
            raise ApiException("Invalid response %s." % resp['status'])
        
        request_token = dict(urlparse.parse_qsl(content))
        
        self.request_token_secret = request_token['oauth_token_secret']
        self.request_token = request_token['oauth_token']
        
        return request_token
        
    def getAccessTokenUrl(self):
        request_token = self.getRequestToken()
        
        return "%s?oauth_token=%s" % (AUTH_URL + "/authorize", request_token['oauth_token'])
    
    def makeRequest(self, url, params, method):
        connection = httplib.HTTPConnection( API_HOST, 80, timeout=10)
        method="POST"
        token = oauth.Token(key=self.access_token, secret=self.access_token_secret)
        base_params = {
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time()),
        }
        params = dict(base_params, **params)

        req = oauth.Request(method=method, url=url, parameters=params)
        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, self.oauth_consumer, token)
        
        headers = {'Content-Type' :'application/x-www-form-urlencoded'}
        connection.request(method, url, body=req.to_postdata(), headers=headers)
        response = connection.getresponse().read()
        
        connection.close()
        
        return response
    
    def setAccessToken(self, access_token, access_token_secret):
        self.access_token = access_token
        self.access_token_secret = access_token_secret
        
    def requestAccessToken(self):
        token = oauth.Token(self.request_token,self.request_token_secret)
        client = oauth.Client(self.oauth_consumer, token)
        
        resp, content = client.request(AUTH_URL + '/access-token', "POST")
        access_token = dict(urlparse.parse_qsl(content))
        
        return access_token
    
    def register(self, email, password):
        token = self.getRequestToken()
        
        params = {
            'email' : email,
            'password' : password,
            'oauth_token' : token[ 'oauth_token' ]
        }
        
        connection = httplib.HTTPConnection( API_HOST, 80, timeout=10)
        connection.request( "GET", API_DOMAIN + '/auth/register?' + urllib.urlencode( params ) )
        connection.getresponse()
        connection.close()
        
        token = self.requestAccessToken()
        
        self.setAccessToken( token[ 'oauth_token' ], token[ 'oauth_token_secret' ] )
        
        return token

    def searchByFile(self, filepath):
        file = open( filepath, 'r' )
        file.seek( 0, 0 )
        file_part = file.read( 1024 * 1024 )
        hash = hashlib.sha1( file_part ).hexdigest()
        file.close()

        params = {
            'hash' : hash,
            'filepath': filepath
        }
        
#        try:
        response = self.makeRequest( API_DOMAIN + "/films/search-by-file", params, 'GET' )
#        except HTTPException:
#            raise ApiException( 'Непредвиденная ошибка API' );

        result = json.loads( response )
        
        return result
        
    def markSeen(self, film_id):
        params = {
            'status' : 'seen',
            'id': film_id
        }
#        try:
        response = self.makeRequest( API_DOMAIN + "/my/films/set-status", params, 'POST' )
        
        result = json.loads( response )
#        except HTTPException as e:
#            if e.code == 403:
#                raise ApiException( 'Нужна авторизация' );
#            elif e.code == 404:
#                raise ApiException( 'Фильм не найден' );
        return result

class ApiException(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)



if __name__ == '__main__':
    api = ApiClient( "832d686803c30887da9e73512289aef404d6e2f68", "718bdd878f2317657deab9936afb4a66" )
    api.register( 'my@email.com','mypass')
    
    
#    api.setAccessToken( '86929e045974f67ad2557e96f397fe7c04d6cc77b', '760635f0167b535660d02d7d1fe2a983' )
#    result = api.searchByFile( '/tmp/Pi_[rutracker.org]_DVO.avi' )
#    film_id = result[ 'id' ]
#    if film_id: 
#        print api.markSeen( film_id )
#    else:
#        print 'no film found :('
